import { create } from 'zustand';

interface TerminalLine {
  id: string;
  content: string;
  type: 'output' | 'error' | 'warning' | 'system' | 'input';
  timestamp: Date;
}

interface TerminalState {
  // 终端状态
  isVisible: boolean;
  lines: TerminalLine[];
  
  // 终端操作
  createLine: (content: string, type?: TerminalLine['type']) => void;
  addOutput: (content: string) => void;
  addOutputLine: (content: string) => void;
  addErrorLine: (content: string) => void;
  addWarningLine: (content: string) => void;
  addSystemLine: (content: string) => void;
  clearOutput: () => void;
  parseOutput: (output: string) => void;
  toggleVisibility: () => void;
  showTerminal: () => void;
  hideTerminal: () => void;
}

const useTerminalStore = create<TerminalState>()((set, get) => ({
  // 初始状态
  isVisible: false,
  lines: [],

  // 创建新行
  createLine: (content: string, type: TerminalLine['type'] = 'output') => {
    const newLine: TerminalLine = {
      id: `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
      content,
      type,
      timestamp: new Date()
    };
    
    set(state => ({
      lines: [...state.lines, newLine]
    }));
  },

  // 添加输出
  addOutput: (content: string) => {
    get().createLine(content, 'output');
  },

  // 添加输出行
  addOutputLine: (content: string) => {
    get().createLine(content, 'output');
  },

  // 添加错误行
  addErrorLine: (content: string) => {
    get().createLine(content, 'error');
  },

  // 添加警告行
  addWarningLine: (content: string) => {
    get().createLine(content, 'warning');
  },

  // 添加系统行
  addSystemLine: (content: string) => {
    get().createLine(content, 'system');
  },

  // 清除输出
  clearOutput: () => {
    set({ lines: [] });
  },

  // 解析输出
  parseOutput: (output: string) => {
    const lines = output.split('\n').filter(line => line.trim());
    lines.forEach(line => {
      if (line.includes('ERROR') || line.includes('error')) {
        get().addErrorLine(line);
      } else if (line.includes('WARNING') || line.includes('warning')) {
        get().addWarningLine(line);
      } else {
        get().addOutputLine(line);
      }
    });
  },

  // 切换可见性
  toggleVisibility: () => {
    set(state => ({ isVisible: !state.isVisible }));
  },

  // 显示终端
  showTerminal: () => {
    set({ isVisible: true });
  },

  // 隐藏终端
  hideTerminal: () => {
    set({ isVisible: false });
  }
}));

export default useTerminalStore;
